<template>
    <div class="page-container">
      <el-row style="margin: 10px 0" justify="space-between">
        <el-row>
          <el-button size="small" type="primary" :icon="Plus" @click="createVisible = 'QUOTATION_ORDER'">新建报价单</el-button>
          <el-button size="small" type="warning" @click="resetParams">全部数据</el-button>
        </el-row>
        <el-row>
          <el-button type="default" size="small" @click="headerVisible = true">表头设置</el-button>
        </el-row>
      </el-row>
  
      <div class="table-box">
        <el-table size="small" :data="tableList" class="table-list" stripe border :cell-style="{textAlign: 'center'}" :header-cell-style="{textAlign: 'center'}">
          <el-table-column v-for="item in header" :key="item.label" :prop="item.label" :min-width="item.width" :class-name="item.label !== 'productName' ? '' : 'order-goods'" align="center">
            <template #header>
              <span v-if="item.label !== 'productName'">{{ item.name }}</span>
              <el-row v-else class="order-row-item order-border-none">
                <el-col :span="6">产品名称</el-col>
                <el-col :span="6">详情规格</el-col>
                <el-col :span="4">数量</el-col>
                <el-col :span="4">单价(元)</el-col>
                <el-col :span="4">小计(元)</el-col>
              </el-row>
              <!-- 可搜索表头 -->
              <el-popover placement="bottom" :width="200" trigger="click" v-if="item.isFilter && item.filter == 'search'">
                <template #reference>
                  <el-icon :size="15" :color="params[item.label] ? 'var(--el-color-warning)' : 'var(--el-color-primary)'" style="margin-left: 2px">
                    <ele-Search/>
                  </el-icon>
                </template>
                <el-input :placeholder="`请输入${item.name}`" v-model.trim="params[item.label]" size="small" clearable @input="getTableList"/>
              </el-popover>
              <!-- 可筛选表头 -->
              <el-popover placement="bottom" :width="120" trigger="click" v-if="item.isFilter && item.filter == 'filter'">
                <template #reference>
                  <el-icon :size="15" :color="params[item.label == 'shortName' ? 'supplierInfoId' : item.label] ? 'var(--el-color-warning)' : 'var(--el-color-primary)'" style="margin-left: 2px">
                    <ele-Filter/>
                  </el-icon>
                </template>
                <el-scrollbar max-height="600px">
                  <el-radio-group v-model="params[item.label == 'shortName' ? 'supplierInfoId' : item.label]" size="small" v-if="filterData[item.label == 'shortName' ? 'supplierInfoId' : item.label] && filterData[item.label == 'shortName' ? 'supplierInfoId' : item.label].length > 0">
                    <el-radio
                        v-for="radio in filterData[item.label == 'shortName' ? 'supplierInfoId' : item.label]"
                        :key="radio.value"
                        :label="radio.value"
                        @click.prevent="radioChange(radio.value, item.label == 'shortName' ? 'supplierInfoId' : item.label)">
                      {{ radio.name }}
                    </el-radio>
                  </el-radio-group>
                  <el-empty style="padding: 0;font-size:12px;" v-else :image-size="50" description="无数据"/>
                </el-scrollbar>
              </el-popover>
            </template>
            <template #default="{row}">
              <div v-if="item.label === 'title'" class="primary" @click="openDetail(row)">{{ row.title }}</div>
              <!-- 产品名称 -->
              <div v-else-if="item.label === 'productList'" style="flex:1;display:flex;flex-direction: column">
                <div v-for="(product, index) in row.productList" :key="product.id" style="flex: 1;height:100%">
                  <el-row class="order-row-item" style="height:100%">
                    <el-col :span="6">{{ product.name }}</el-col>
                    <el-col :span="6">{{ product.specs?product.specs:'无' }}</el-col>
                    <el-col :span="4">{{ product.quantity }}</el-col>
                    <el-col :span="4">{{ product.price.toFixed(2) }}</el-col>
                    <el-col :span="4">{{ (product.quantity * product.price ).toFixed(2) }}</el-col>
                  </el-row>
                  <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)" v-if="index < row.productList.length - 1"/>
                </div>
              </div>
              <div v-else-if="item.label === 'approveState'">{{ row.approve == 0 && row.approveState == 1 ? '无需审批' : (row.approve == 1 && row.approveState == 1 ? '已审批' : (row.approve == 1 && row.approveState == 2?'待审批':'待发起申请')) }}</div>
              <div v-else>{{ row[item.label] }}</div>
            </template>
  
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="130" align="center">
            <template v-slot="{row}">
              <el-button size="small" type="primary" link @click="approval(row)" v-if="row.approve == 0 && row.approveState == 2">审批</el-button>
              <el-button size="small" type="primary" link @click="removeQuotation(row)">删除</el-button>
              <el-button size="small" type="primary" link @click="toPurchase(row)" :disabled="row.approveState != 1">生成订单</el-button>
            </template>
          </el-table-column>
          <el-table-column label="发送方式" fixed="right" width="90" align="center">
            <template v-slot="{row}">
              <el-button size="small" type="primary" link v-if="existOppositeList(row)" @click="directSend(row)"><i class="fa fa-envelope-o"/>直发</el-button>
              <el-button size="small" type="primary" link v-else @click="wechatSend(row)"><i class="fa fa-weixin"/>微信</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
  
      <div class="page-block">
        <el-pagination v-model:currentPage="params.current" v-model:page-size="params.size" :page-sizes="[10, 20, 30, 40]" :small="true" :disabled="false" :background="false" layout="total, sizes, prev, pager, next, jumper" :total="total" :hide-on-single-page="true" @size-change="sizeChange" @current-change="currentChange"/>
      </div>
  
      <!-- 表头设置对话框 -->
      <el-dialog title="表头设置" v-model="headerVisible" destroy-on-close width="40%" @close="headerVisible = false" @opened="dialogOpened" top="5vh">
        <el-table ref="tableHeaderRef" :data="allHeader" @selection-change="headerChange" stripe border :cell-style="{textAlign: 'center'}" row-key="label"
                  :header-cell-style="{textAlign: 'center', background: 'var(--el-color-primary-light-9)', color: 'var(--next-bg-menuBar-light-1)'}">
          <el-table-column type="selection" width="90"/>
          <el-table-column label="表头名称" prop="name"/>
        </el-table>
        <template #footer>
          <el-button size="small" @click="headerVisible = false">关闭</el-button>
          <el-button size="small" type="primary" @click="submitHeader">保存</el-button>
        </template>
      </el-dialog>
  
      <quotation-order v-model:code="createVisible" @callback="createCallback"/>
      <!-- 详情 -->
      <quotation-detail v-model:drawer="detailDrawer" v-model:quotation="detailData" @callback="getTableList"/>
      <!-- 转订单 -->
      <create-order v-model:dialogDrawer="dialogCreate" v-model:defaultForm="orderForm" v-model:entrance="entrance" @onSubmit="goOrderPage"></create-order>
    </div>
  </template>
  
  <script>
  import {onMounted, reactive, toRefs, ref} from 'vue'
  import {Plus, Search} from '@element-plus/icons-vue'
  import { useRouter } from 'vue-router'
  import QuotationOrder from '/@/views/order/components/QuotationOrder.vue'
  import QuotationDetail from '/@/views/order/components/QuotationDetail.vue'
  import CreateOrder from '/@/views/order/components/CreateOrder.vue'
  import {getHeaders, saveHeader, sendQuote} from '/@/api/supplier/quoteOrder'
  import {ElMessage, ElMessageBox} from 'element-plus'
  import {getSupplierSelector} from '/@/api/supplier'

  import api from '/@/api/commonApi'
  
  export default {
    name: 'Quotation',
    components: {
      QuotationOrder,
      QuotationDetail,
      CreateOrder
    },
    setup() {
      const router = useRouter()
      const tableHeaderRef = ref()
      const state = reactive({
        params: {
          current: 1,
          size: 10,
          quoteNo: null,
          title: null,
          approveState: null
        },
        tableList: [],
        total: 0,
        header: [],
        allHeader: [
          {
            name: '报价单号',
            isFilter: true,
            filter: 'search',
            label: 'quoteNo',
            width: '140',
            sort: 0
          }, {
            name: '报价主题',
            isFilter: true,
            filter: 'search',
            label: 'title',
            width: '120',
            sort: 1
          }, {
            name: '客户',
            isFilter: true,
            filter: 'filter',
            label: 'customerName',
            width: '100',
            sort: 2
          }, {
            name: '报价金额',
            isFilter: false,
            filter: '',
            label: 'amount',
            width: '90',
            sort: 3
          }, {
            name: '产品清单',
            isFilter: false,
            filter: '',
            label: 'productList',
            width: '600',
            sort: 4
          }, {
            name: '审批状态',
            isFilter: true,
            filter: 'filter',
            label: 'approveState',
            width: '90',
            sort: 5
          }, {
            name: '备注',
            isFilter: false,
            filter: '',
            label: 'remark',
            width: '100',
            sort: 6
          }
        ],
        selectedHeader: [],
        headerVisible: false,
        filterData: {
          approveState: [{name: '无需审批', value: 0}, {name: '已审批', value: 1}, {name: '未审批', value: 2}],
          supplierInfoId: []
        },
        createVisible: '',    // QUOTATION_ORDER
        editData: null,
        orderForm: {},
        dialogCreate: false,
        detailDrawer: false,
        detailData: {},
        entrance: 'QUOTE_ORDER',
        suppLierList: [],
      })
  
      const sizeChange = (size) => {
        state.params.size = size
        currentChange(1)
      }
      const currentChange = (current) => {
        state.params.current = current
        getTableList()
      }
      const getTableList = () => {
        api.customerQuotes(state.params).then(res => {
          state.total = res.data.total
          state.tableList = res.data.records
        })
      }
      // 直发
      const directSend = (quotation) => {
        ElMessageBox.confirm('确定把报价单 “' + quotation.title + '” 发送给对方？', '提示', {
          confirmButtonText: '发送',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          sendQuote(quotation).then(res => {
            if (res.data) {
              ElMessage.success('发送成功!')
            }
          }).catch(e => console.log(e))
        }).catch(err => console.log(err))
      }
      // 微信转发
      const wechatSend = (quotation) => {
        navigator.clipboard.writeText(import.meta.env.VITE_SHARE_URL + '/quotationOrder/' + quotation.id).then(() => ElMessage.success('复制成功！'))
      }
      // 删除报价单
      const removeQuotation = (quotation) => {
        ElMessageBox.confirm('确定删除 “' + quotation.title + '” 报价单？', '提示', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          api.removeOrderQuote({ids: quotation.id}).then(res => {
            if (res.data) {
              ElMessage.success('删除成功！')
              getTableList()
            }
          })
        }).catch(err => console.log(err))
  
      }
      // 生成销售单
      const toPurchase = (quotation) => {
        api.orderSkuList(quotation.productList).then(res => {
          state.orderForm = {
            classOther: 0,
            createTime: null,
            customerId: quotation.customerId,
            customerName: quotation.customerName,
            memberUsername: quotation.customerName,
            forCustomerId: quotation.contactId,
            forCustomerName: quotation.contactName,
            forEnterpriseId: '',
            forEnterpriseName: '',
            receiverName: quotation.contactName,
            receiverPhone: '',
            receiverProvince: '',
            receiverCity: '',
            receiverRegion: '',
            receiverDetailAddress: '',
            totalAmount: quotation.amount,
            payAmount: (quotation.amount * (1 - quotation.primeRate)).toFixed(2),
            settlement: Number(quotation.paymentType),
            payType: null,
            belongerId: quotation.userId,
            belongerName: '',
            payStatus: 0,
            status: 0,
            logisticStatus: 0,
            deliveryCompany: null,
            contractFileUrl: '',
            note: '报价单转订单',
            deliveryType: 0,
            saveAndSend: true,
            isApprove: 0,
            approveState: 2,
            orderItemList: res.data,
          }
          state.dialogCreate = true
        })
      }
      // 打开详情
      const openDetail = (quotation) => {
        state.detailData = JSON.parse(JSON.stringify(quotation))
        state.detailDrawer = true
      }
      // 筛选
      const radioChange = (val, name) => {
        // 重复点击同个值取消选中
        state.params[name] = state.params[name] == val ? null : val
        getTableList()
      }
      // 重置参数
      const resetParams = () => {
        state.params = {
          current: 1,
          size: 10,
          quoteNo: null,
          title: null,
          supplierInfoId: null,
          approveState: null
        }
        getTableList()
      }
      // 表头对话框的回调
      const dialogOpened = () => {
        state.header.forEach(item => {
          state.selectedHeader.push(item)
          tableHeaderRef.value.toggleRowSelection(item, true)
        })
      }
      const headerChange = (list) => {
        if (state.selectedHeader.length > list.length) {
          state.selectedHeader = list
        } else {
          const item = list[list.length - 1]
          state.selectedHeader.splice(item.sort, 0, item)
        }
      }
      // 保存表头数据
      const submitHeader = () => {
        saveHeader(state.selectedHeader).then(res => {
          state.header = Object.assign([], state.selectedHeader)
          state.headerVisible = false
          ElMessage.success('保存成功！')
        }).catch(e => console.log(e))
      }
      // 创建框关闭回调
      const createCallback = () => {
        getTableList()
      }
      // 前往订单页面
      const goOrderPage = () => {
        getTableList()
        router.push({
            path: '/order/list'
        })
      }
      // 审批
      const approval = (row) => {
        ElMessageBox.confirm(
            `是否发起审批？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true,
            }
        ).then(() => {
            row.matter = 1
            api.quoteSyncPurchase(row).then(res => {
                getList()
                ElMessage.success(res.data.isApprove == '0'?"报价单已审批":"提起审批成功")
            })
        }).catch(() => {

        })
      }
      // 获取我在谁的供应商列表
      const existWhoSupplierList = () => {
        api.myExistSupplierList().then(res => {
          state.suppLierList = res.data
        })
      }
      // 显示直发按钮
      const existOppositeList = (data) => {
        if (data.orderId) {
          return false
        } else {
          // 客户关联的用户id
          let result = false
          result = state.suppLierList.find(item => {
            if (data.contactsMap.sysUserId) {
              if (item.purchaseUserId == data.contactsMap.sysUserId){
                return true
              }
            }
          })
          return result || false
        }
      }
  
      onMounted(() => {
        getHeaders().then(res => {
          if (res.data && res.data.length > 0) {
            res.data.forEach(item => {
              for (let i = 0; i < state.allHeader.length; i++) {
                let headerItem = state.allHeader[i]
                if (item.label == headerItem.label) {
                  state.header.push(headerItem)
                }
              }
            })
          } else {
            state.header = state.allHeader
          }
        }).catch(e => console.log(e))
        // 获取供应商列表
        state.filterData.supplierInfoId = []
        getSupplierSelector().then(res => res.data.forEach(item => state.filterData.supplierInfoId.push({name: item.shortName, value: item.supplierInfoId})))
        getTableList()
        existWhoSupplierList()
      })
  
      return {
        Plus,
        Search,
        ...toRefs(state),
        tableHeaderRef,
        sizeChange,
        approval,
        currentChange,
        getTableList,
        directSend,
        wechatSend,
        removeQuotation,
        toPurchase,
        openDetail,
        radioChange,
        resetParams,
        dialogOpened,
        headerChange,
        submitHeader,
        createCallback,
        goOrderPage,
        existWhoSupplierList,
        existOppositeList,
      }
    }
  }
  </script>
  
  <style scoped lang="scss">
  .page-container {
    .page-row {
      display: flex;
      flex-wrap: wrap;
      align-items: stretch;
  
      .tips-data {
        display: flex;
        align-items: center;
        height: 28px;
        margin-top: 20px;
  
        .tips {
          margin-right: 3px;
          font-size: 13px;
        }
  
        &:first-child {
          height: unset;
          margin-top: 0;
        }
      }
  
      .tips-cell {
        flex: auto;
  
        .tips-item {
          display: flex;
          align-items: center;
          padding-left: 10px;
          justify-content: space-between;
        }
  
        .tips-name {
          margin-right: 10px;
          flex: 1;
          overflow: hidden;
          text-align: center;
        }
  
        .item-data {
          text-align: center;
          height: 28px;
          margin-top: 20px;
          line-height: 28px;
          color: var(--el-menu-text-color);
          font-size: 13px;
        }
  
        .text-red {
          font-size: 24px;
          color: red;
        }
  
        .item-right {
          margin-right: 14px;
        }
  
        .red {
          color: var(--el-color-danger)
        }
  
        .green {
          color: var(--el-color-success);
        }
      }
  
      :deep(.el-table--border::before),
      :deep(.el-table--border::after),
      :deep(.el-table__inner-wrapper::before),
      :deep(.el-table__border-left-patch) {
        display: none;
      }
  
      :deep(.el-table--border .el-table__inner-wrapper tr:first-child th:first-child),
      :deep(.el-table--border .el-table__inner-wrapper tr:first-child td:first-child) {
        border-left: none !important;
      }
  
      :deep(.el-table--border .el-table__cell:last-child) {
        border-right: none;
      }
  
      :deep(.el-table__row) {
        &:last-child {
          .el-table__cell {
            border-bottom: none;
          }
        }
      }
    }
  
    .table-box {
      background: #fff;
      margin-top: 10px;
  
      :deep(.el-table__header-wrapper .el-table__cell) {
        background: var(--el-color-primary-light-9);
        color: var(--next-bg-menuBar-light-1);
      }
  
      :deep(thead .cell) {
        display: flex;
        align-items: center;
        justify-content: center;
      }
  
      :deep(thead .el-icon) {
        margin-top: -2px;
        cursor: pointer;
      }
  
      .primary {
        cursor: pointer;
        color: var(--el-color-primary);
      }
  
      .short {
        display: block;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
  
      .table-list {
        border: 1px solid var(--el-table-border-color);
        border-bottom: none;
  
        :deep(thead .cell) {
          display: flex;
          align-items: center;
          justify-content: center;
        }
  
        :deep(thead th:last-child .cell) {
          justify-content: center;
        }
  
        :deep(thead .el-icon) {
          margin-top: -2px;
          cursor: pointer;
        }
  
        .primary {
          cursor: pointer;
          color: var(--el-color-primary);
        }
  
        :deep(.el-button) {
          margin-left: 0;
          margin-right: 12px;
        }
  
        :deep(.el-table__body td.el-table__cell) {
          border-right: 1px solid var(--el-border-color-light);
          padding: 0;
  
          &:last-child {
            border-right: none;
          }
        }
  
        .order-row-item {
          width: 100%;
  
          :deep(.el-col) {
            border-right: 1px solid var(--el-border-color-light);
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
  
            &:last-child {
              border-right: none;
            }
  
            &:first-child,
            &:nth-child(2) {
              text-align: left;
              justify-content: flex-start;
              padding-left: 8px;
            }
          }
        }
  
        .order-border-none {
          :deep(.el-col) {
            border: none;
          }
        }
      }
    }
  }
  </style>
  <style lang="scss">
  .el-table__body .order-goods .cell {
    min-height: 70px;
    display: flex;
    align-items: stretch;
    padding: 0;
  }
  </style>
  